package com.linkage.jz.bankruptcy.fragment;

import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingPhoneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.fragment.Message.MsgBBSFragment;
import com.linkage.jz.bankruptcy.fragment.Message.MsgNoticeFragment;
import com.linkage.jz.bankruptcy.fragment.Message.MsgWordsFragment;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.fragment.BaseNoticeFragment;
import com.linkage.seapeak.fragment.ConversationBBSFragment;
import com.linkage.seapeak.fragment.ConversationChatFragment;
import com.linkage.seapeak.fragment.ConversationNoticeFragment;
import com.linkage.seapeak.net.ResultCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by caobotao on 16/1/4.
 */
public class MsgFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private Button topBtn01, topBtn02, topBtn03;
    private LinearLayout topBtnContainer;
    private ViewPager mViewPager;
    private TextView id_dcphGroup_unreadbt1, id_dcphGroup_unreadbt2, id_dcphGroup_unreadbt3;
    private TabPagerAdapter mPagerAdapter;
    ArrayList<BaseNoticeFragment> fragments = new ArrayList<BaseNoticeFragment>();
    private ShapeLoadingDialog shapeLoadingDialog;
    View view = null;

//    当前选中项
    public int selectPosition = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_tab_msg, container, false);
            shapeLoadingDialog = new ShapeLoadingDialog(getActivity());

            ActionBar bar = getActivity().getActionBar();
            if (bar != null) {
                bar.hide();
            }

            init(view);
            EventBus.getDefault().register(this);
        }

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        getUnReadNum();
        try {
            fragments.get(selectPosition).checkItems();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PublicNoticeDialog noticeDialog;

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
//                    finish();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();
//                    finish();
                    break;

                case R.id.btn_save_notice:
                    readoneAll();
                    noticeDialog.dismiss();
                    break;

            }
        }
    };

    @Subscribe
    public void getEventBus(UnreadMsg num) {
        getUnReadNum();
    }

    @Subscribe
    public void getEventBus(ClearUnread num) {
        noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
                1, "提示", "此操作会将未读的消息全部标记为已读",
                "取消", "确认");
        noticeDialog.show();
    }

    /**
     * 为了防止混淆更新消息的EventBus与其他管道重合
     */
    public static class UnreadMsg {
    }

    public static class ClearUnread {
    }

    private void init(View view) {
        fragments.add(ConversationNoticeFragment.newInstance());
        fragments.add(ConversationChatFragment.newInstance());
        fragments.add(ConversationBBSFragment.newInstance());

        topBtn01 = (Button) view.findViewById(R.id.id_dcphGroup_topBtn01);
        topBtn02 = (Button) view.findViewById(R.id.id_dcphGroup_topBtn02);
        topBtn03 = (Button) view.findViewById(R.id.id_dcphGroup_topBtn03);
        id_dcphGroup_unreadbt1 = view.findViewById(R.id.id_dcphGroup_unreadbt1);
        id_dcphGroup_unreadbt2 = view.findViewById(R.id.id_dcphGroup_unreadbt2);
        id_dcphGroup_unreadbt3 = view.findViewById(R.id.id_dcphGroup_unreadbt3);
        id_dcphGroup_unreadbt1.setVisibility(View.GONE);
        id_dcphGroup_unreadbt2.setVisibility(View.GONE);
        id_dcphGroup_unreadbt3.setVisibility(View.GONE);
        topBtnContainer = (LinearLayout) view.findViewById(R.id.id_dcphGroup_topBtn_container);
        topBtn01.setOnClickListener(this);
        topBtn02.setOnClickListener(this);
        topBtn03.setOnClickListener(this);
        mViewPager = (ViewPager) view.findViewById(R.id.id_dcphGroup_viewPager);
        mPagerAdapter = new TabPagerAdapter(getChildFragmentManager(), fragments);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.invalidate();
        mPagerAdapter.notifyDataSetChanged();
        changeFragmentFocus(0);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(6);
    }

    /*
     * 自定义FragmentStatePagerAdapter适配器来显示滑动Fragment
     * */
    private class TabPagerAdapter extends FragmentStatePagerAdapter implements
            ViewPager.OnPageChangeListener {

        private ArrayList<BaseNoticeFragment> objects;

        public TabPagerAdapter(FragmentManager fm, ArrayList<BaseNoticeFragment> objects) {
            super(fm);
            this.objects = objects;
            mViewPager.setOnPageChangeListener(this);
        }

        @Override
        public Fragment getItem(int position) {
            return objects.get(position);
        }

        @Override
        public int getCount() {
            return objects.size();
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//            super.destroyItem(container, position, object);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //滑动的监听事件
            selectPosition = position;
            fragments.get(position).checkItems();
            changeFragmentFocus(position);
        }
    }


    private void changeFragmentFocus(int focus) {
        if (focus == 0) {
            topBtn01.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn_press);
            topBtn02.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn03.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.page_top));
            topBtn02.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn03.setTextColor(getResources().getColor(R.color.text_secondary_color));
        } else if (focus == 1) {
            topBtn01.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn02.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn_press);
            topBtn03.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn02.setTextColor(getResources().getColor(R.color.page_top));
            topBtn03.setTextColor(getResources().getColor(R.color.text_secondary_color));
        } else if (focus == 2) {
            topBtn01.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn02.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn);
            topBtn03.setBackgroundResource(R.drawable.fragment_tab_msg_corner_btn_press);
            topBtn01.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn02.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn03.setTextColor(getResources().getColor(R.color.page_top));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.id_dcphGroup_topBtn01:
                changeFragmentFocus(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.id_dcphGroup_topBtn02:
                changeFragmentFocus(1);
                mViewPager.setCurrentItem(1);
                break;
            case R.id.id_dcphGroup_topBtn03:
                changeFragmentFocus(2);
                mViewPager.setCurrentItem(2);
                break;
            default:
                break;
        }
    }

    /**
     * 全部已读消息
     */
    public void readoneAll() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            Log.i("BaseNoticeFragment", "readone: token为空");
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .readoneAll(userToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        shapeLoadingDialog.dismiss();
                        try {
                            if (json.get("code").getAsInt() == 0) {
                                fragments.get(mViewPager.getCurrentItem()).onResume();
                                getUnReadNum();
                            } else {
                                ToastUtil.showShort("请求失败");
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            ToastUtil.showShort("请求失败");
                        }
                    }

                    @Override
                    public void onCompleted() {
                        shapeLoadingDialog.dismiss();
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        shapeLoadingDialog.dismiss();
                        ToastUtil.showShort("请求失败");
                    }
                });
    }


    public void getUnReadNum() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null || "".equalsIgnoreCase(userToken)) {
            id_dcphGroup_unreadbt1.setVisibility(View.GONE);
            id_dcphGroup_unreadbt2.setVisibility(View.GONE);
            id_dcphGroup_unreadbt3.setVisibility(View.GONE);

            Log.i("zhong", "getUnReadNum false");
            EventBus.getDefault().post(new MainActivity.ShowHideClearAll(false));
            return;
        }

//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";


        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .build();

        String url = Consts.WEBURL_UNREADCOUNT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }

                String str = response.body().string();
                Log.i(TAG, " UNREAD ======== onResponse: " + str);

                try {
                    final JSONObject object = new JSONObject(str);
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if (object.optInt("code") == 0) {
                        JSONObject dataobject = object.optJSONObject("data");
                        final String noticeCount = dataobject.optString("noticeCount");
                        final String stayCount = dataobject.optString("stayCount");
                        final String forumCount = dataobject.optString("forumCount");

//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                if ("0".equalsIgnoreCase(noticeCount)) {
                                    id_dcphGroup_unreadbt1.setVisibility(View.GONE);
                                } else {
                                    id_dcphGroup_unreadbt1.setVisibility(View.VISIBLE);
                                    id_dcphGroup_unreadbt1.setText("  " + noticeCount + "  ");
                                }
                                if ("0".equalsIgnoreCase(stayCount)) {
                                    id_dcphGroup_unreadbt2.setVisibility(View.GONE);
                                } else {
                                    id_dcphGroup_unreadbt2.setVisibility(View.VISIBLE);
                                    id_dcphGroup_unreadbt2.setText("  " + stayCount + "  ");
                                }
                                if ("0".equalsIgnoreCase(forumCount)) {
                                    id_dcphGroup_unreadbt3.setVisibility(View.GONE);
                                } else {
                                    id_dcphGroup_unreadbt3.setVisibility(View.VISIBLE);
                                    id_dcphGroup_unreadbt3.setText("  " + forumCount + "  ");
                                }
                            }

                        });

                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                id_dcphGroup_unreadbt1.setVisibility(View.GONE);
                                id_dcphGroup_unreadbt2.setVisibility(View.GONE);
                                id_dcphGroup_unreadbt3.setVisibility(View.GONE);
                            }

                        });
                    }


                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
